from Pojo import User
from flask import request

# 先验证用户名和密码是否对应，再根据uid生成token并返回
def getJWT():
    input_uid = request.form.get("uid")
    input_password = request.form.get("password")
    try:
        user = User.query.get(int(input_uid))
        user_password = user.password
        if user_password == input_password:
            import jwt
            import time
            d = {
                # 公共声明，时间戳以秒为单位，每60个单位为1分钟，
                'exp': time.time() + 60 * 60 ,  # (Expiration Time) 此token的过期时间的时间戳
                'iat': time.time(),  # (Issued At) 指明此创建时间的时间戳
                'iss': 'Issuer',  # (Issuer) 指明此token的签发者
                # 私有声明
                'data': {
                    'username': input_uid,
                    'timestamp': time.time()
                }
            }
            jwt_encode = jwt.encode(d, '20191120239', algorithm='HS256')
            return jwt_encode

    except:
        return "请检查用户名或密码"

# 验证用户的Token是否过期，可以通过Token获取用户的唯一标识符uid
def verifyJWT():
    user_token = request.headers.get('Authorization')
    return getUidFromToken(user_token)


def getUidFromToken(token):
    import jwt
    try:
        payload = jwt.decode(token, key='20191120239', algorithms='HS256')
        # print(payload)
        user_uid = payload['data']['username']
        # print(payload)
        return user_uid
    except:
        return "Token已过期或无效"